package org.chs.ts.system.service.impl;

import lombok.extern.slf4j.Slf4j;

import org.chs.ts.system.service.ILoginService;
import org.chs.ts.system.vo.SysUserVO;
import org.chs.ts.vo.Result;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Objects;

/**
 * @author wuwei
 * @date 2024/1/2
 * @apiNote
 */
@Service
@Slf4j
public class LoginServiceImpl implements ILoginService {

    private final String REDIS_PREFIX = "login:";

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisCache redisCache;

    @Override
    public Result login(SysUserVO user) {

        UsernamePasswordAuthenticationToken usernamePasswordToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordToken);

        if (Objects.isNull(authenticate)) {
            throw new UserLoginException(UserLoginExceptionTypeEnum.UN_CHECK_PWD);
        }

        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

        // 生成用户token
        String token = JwtUtils.createJWT(loginUser.getSysUser().getId().toString());
        log.info("token -> {}",token);
        HashMap<String, String> map = new HashMap<>();
        map.put("token", token);

        // 存入redis

        redisCache.setCacheObject(REDIS_PREFIX + loginUser.getSysUser().getId().toString(), loginUser);

        return Result.ok("登录成功!");

    }

    @Override
    public Result logout() {

        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        redisCache.deleteObject(REDIS_PREFIX + loginUser.getSysUser().getId().toString());

        return Result.ok("登出成功!");
    }
}
